package org.example.Server.controller;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class RetryInterceptor implements Interceptor {
    private final int maxRetries;
    private final int retryDelayMillis;

    public RetryInterceptor(int maxRetries, int retryDelayMillis) {
        this.maxRetries = maxRetries;
        this.retryDelayMillis = retryDelayMillis;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = null;
        IOException lastException = null;

        for (int attempt = 0; attempt <= maxRetries; attempt++) {
            // 关闭之前的响应（如果有）
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {
                    // 记录关闭失败的日志，但不影响重试逻辑
                    System.err.println("Failed to close previous response: " + e.getMessage());
                }
            }

            try {
                response = chain.proceed(request);
                if (response.isSuccessful()) {
                    return response;
                } else {
                    // 处理非2xx响应
                    lastException = new IOException("Request failed with code " + response.code());
                }
            } catch (IOException e) {
                lastException = e;
            }

            // 如果不是最后一次尝试，则进行重试
            if (attempt < maxRetries) {
                try {
                    Thread.sleep(retryDelayMillis);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new IOException("Retry interrupted", e);
                }
                System.out.println("Retrying request (" + (attempt + 1) + "/" + maxRetries + ")");
            }
        }

        // 所有重试都失败后，关闭最后一个响应并抛出异常
        if (response != null) {
            response.close();
        }

        if (lastException != null) {
            throw lastException;
        }

        throw new IOException("Max retries exceeded without a response");
    }
}
